package interfaces;

import JDBC.Constants;
import JDBC.DBConnection;
import Model.Estabelecimento;
import view.TelaConsulta;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * Created with IntelliJ IDEA.
 * User: J-Pac123
 * Date: 5/10/14
 * Time: 6:58 PM
 * To change this template use File | Settings | File Templates.
 */
public class SugestoesEstabelecimentosService implements SugestoesEstabelecimentos {

    private static SugestoesEstabelecimentosService service;
    private ServiceLoader<SugestoesEstabelecimentos> loader;

    private SugestoesEstabelecimentosService() {
        loader = ServiceLoader.load(SugestoesEstabelecimentos.class);
    }

    public static synchronized SugestoesEstabelecimentosService getInstance() {
        if(service == null) {
            service = new SugestoesEstabelecimentosService();
        }
        return service;
    }

    // O acesso à bd é feito directamente, sem seguir a arquitectura MVC porque nao foi especificada, tal como nao o foi a interface --- Relatorio
    @Override
    public void verSugestoes(String email) {

        System.out.println("verSugestoes: email - " + email);
        DBConnection dbConnection = new DBConnection(Constants.DB_NAME, Constants.USER, Constants.PASSWORD, false, null);
        String query = "select e.idEstabelecimento as Id, e.designacao as Nome, z.designacao as Zona, rating as Avaliacao from Zona z inner join Estabelecimento e inner join Utilizador u where u.email = '" + email + "'";
        DBConnection.ConnectionHandler ch = new DBConnection.ConnectionHandler();
        dbConnection.returnResultSetSelectStatement(query, 1, ch);

        List<Estabelecimento> sugestoes = new ArrayList<Estabelecimento>();
        try {
            while (ch.r.next()) {
                Estabelecimento estabelecimento = new Estabelecimento(ch.r.getInt("Id"), ch.r.getString("Nome"), ch.r.getString("Zona"), ch.r.getInt("Avaliacao"));
                sugestoes.add(estabelecimento);
            }
            ch.r.close();
            dbConnection.closeDatabase();

            final Estabelecimento[] sugestoesArray = sugestoes.toArray(new Estabelecimento[0]);

            if(sugestoesArray.length != 0) {
                TelaConsulta telaConsulta = new TelaConsulta();
                telaConsulta.display(sugestoesArray);
            }

        } catch (SQLException e) {
            e.printStackTrace();
            dbConnection.closeDatabase();
        }

    }


}
